package com.dreamer.repository.lottery;

import com.dreamer.domain.lottery.Gift;
import com.dreamer.domain.lottery.Player;
import com.dreamer.repository.mobile.BaseDaoImpl;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by huangfei on 06/07/2017.
 */
@Repository
public class PlayerDao extends BaseDaoImpl<Player>{

//    /**
//     * 找出当前活动所有的参与者
//     * @param lid
//     * @return
//     */
//  public List<Player> selectByLid(Integer lid){
//       String hql = "from Player player where player.lid = :lid ";
//       Query query = getSessionFactory().getCurrentSession().createQuery(hql);
//       query.setParameter("lid",lid);
//       return query.list();
//   }

    public List<Integer> findByLidAndLimit(Integer lid,Integer start,Integer limit){
        String sql =  "select id from player where lid = :lid";
        Query query = getSessionFactory().getCurrentSession().createNativeQuery(sql);
        query.setParameter("lid",lid);
        query.setFirstResult(start);
        query.setMaxResults(limit);
        return query.list();
    }


    /**
     * 找出某人参与某个活动的记录
     * @param uid
     * @param lid
     * @return
     */
    public List<Player> findByLidAndUid(Integer uid,Integer lid){
        String hql = "from Player player where player.uid = :uid and player.lid = :lid";
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        query.setParameter("uid",uid);
        query.setParameter("lid",lid);
        return query.list();
    }

    /**
     * 找出某人还没抽的
     * @param uid
     * @param lid
     * @return
     */
    public Player findByLidAndUidNotGived(Integer uid,Integer lid){
        String hql = "from Player player where player.uid = :uid and player.lid = :lid and player.open = :open and player.gived != :gived ";
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        query.setParameter("uid",uid);
        query.setParameter("lid",lid);
        query.setParameter("open",true);
        query.setParameter("gived",true);
        query.setMaxResults(1);
        return (Player) query.uniqueResult();
    }



    /**
     * 找出最后一个中奖者的ID
     * @param number
     * @return
     */
   public Integer findLast(Integer number){
      String sql = "select max(id) from (select id from player limit :number) as tt";
      Query query = getSessionFactory().getCurrentSession().createNativeQuery(sql);
      query.setParameter("number",number);
      return (Integer) query.uniqueResult();
   }

    /**
     * 激活最后一个抽奖者之前的所有人可以参与抽奖
     * @param id 最后一个人的ID
     */
   public void actPlayer(Integer id){
      String hql = "update Player player set player.open = true where player.open = false  and player.id <= :id";
      Query query = getSessionFactory().getCurrentSession().createQuery(hql);
      query.setParameter("id",id);
      query.executeUpdate();
   }

}
